import uvicorn
from tortoise.contrib.fastapi import register_tortoise
from fastapi import FastAPI

from models.models import User

app = FastAPI()

#绑定数据库
register_tortoise(app,
                  db_url="mysql://root:root@localhost:3306/python-example",
                  modules={"models":['models.models']},  #模型,取代sql语句, models里面所以的class对应各自的数据表,
                  generate_schemas=True,   #根据模型,自动给数据库创建一张表
                  add_exception_handlers=True
                  )
#读取记录
@app.get("/example4_1")
async def example4_1():
    users = await User.all()
    print(users)
    return users
#创建一条记录
@app.get("/example4_2")
async def example4_2():
    await User(username="bbb", password="bbb", name="bbb1").save()
    return 'ok'
#筛选记录
@app.get("/example4_3")
async def example4_3():
    filter_resoult = await User.filter(username__icontains="bbb").all()
    return filter_resoult


if __name__ == '__main__':
    uvicorn.run(app, port=9102)


